package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/7/26 15:21
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/payment/alipay")
public class AlipayApiController {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${app_id}")
    private String app_id;

    //  http://api.gmall.com/api/payment/alipay/submit/45
    @GetMapping("submit/{orderId}")
    public String paySubmit(@PathVariable Long orderId){
        //  调用服务层方法
        String from = alipayService.createPay(orderId);
        //  返回
        return from;
    }


    //  调整到支付成功页面. 想办法跳转到web-all/gmall-web
    @GetMapping("/callback/return")
    public void callbackReturn(HttpServletResponse response){
        //  void
        try {
            response.sendRedirect(AlipayConfig.return_order_url);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //  String 重定向
        //  return "redirect:"+ AlipayConfig.return_order_url;
    }

    //  http://n5nkak.natappfree.cc/api/payment/alipay/callback/notify
    //  https: //商家网站通知地址?voucher_detail_list=[{"amount":"0.20","merchantContribute":"0.00","name":"5折券","otherContribute":"0.20","type":"ALIPAY_DISCOUNT_VOUCHER","voucherId":"2016101200073002586200003BQ4"}]&fund_bill_list=[{"amount":"0.80","fundChannel":"ALIPAYACCOUNT"},{"amount":"0.20","fundChannel":"MDISCOUNT"}]&subject=PC网站支付交易&trade_no=2016101221001004580200203978&gmt_create=2016-10-12 21:36:12&notify_type=trade_status_sync&total_amount=1.00&out_trade_no=mobile_rdm862016-10-12213600&invoice_amount=0.80&seller_id=2088201909970555&notify_time=2016-10-12 21:41:23&trade_status=TRADE_SUCCESS&gmt_payment=2016-10-12 21:37:19&receipt_amount=0.80&passback_params=passback_params123&buyer_id=2088102114562585&app_id=2016092101248425&notify_id=7676a2e1e4e737cff30015c4b7b55e3kh6& sign_type=RSA2&buyer_pay_amount=0.80&sign=***&point_amount=0.00
    @PostMapping("/callback/notify")
    public String callbackNotify(@RequestParam HashMap<String,String> paramsMap ){
        System.out.println("paramsMap:\t"+paramsMap);
        //  必须是这个success字符,否则认为通知失败.
        //  触发重发策略：4m、10m、10m、1h、2h、6h、15h --> 要考虑幂等性. 支付宝针对同一条异步通知重试时，异步通知参数中的 notify_id 是不变的
        //  Map<String, String> paramsMap = ... //将异步通知中收到的所有参数都存放到map中
        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(paramsMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(signVerified){
            //  获取商户传递的订单号
            String outTradeNo = paramsMap.get("out_trade_no");
            //  异步传递的总金额
            String totalAmount = paramsMap.get("total_amount");
            //  获取支付产品的APPID
            String appId = paramsMap.get("app_id");
            String tradeStatus = paramsMap.get("trade_status");
            //  获取notify_id
            String notifyId = paramsMap.get("notify_id");

            //  支付宝针对同一条异步通知重试时，异步通知参数中的 notify_id 是不变的。
            //  利用传递的商户订单号查询paymentInfo 或 orderInfo.
            PaymentInfo paymentInfoQuery = paymentService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            //  out_trade_no total_amount seller_id app_id TRADE_SUCCESS 或 TRADE_FINISHED
            //  测试支付的时候给的金额是0.01; 而payment_info 中是实际的总金额。 paymentInfoQuery.getTotalAmount().compareTo(new BigDecimal(totalAmount))!=0
            //  如果实际开发中，还可以 通过 out_trade_no and total_amount and seller_id 查询记录
            if (null == paymentInfoQuery || new BigDecimal("0.01").compareTo(new BigDecimal(totalAmount))!=0
            || !app_id.equals(appId)){
                return "failure";
            }
            //  如何保证消息幂等性setnx key value; 过期时间是多久. 24h24m 4m、10m、10m、1h、2h、6h、15h
            Boolean result = this.redisTemplate.opsForValue().setIfAbsent(notifyId, notifyId, 24 * 60 + 24, TimeUnit.MINUTES);
            //  result = true; 说明第一次执行. result = false; 说明你是重发的消息.
            if (!result){
                //  说明里面有人消费这个消息.
                return "failure";
            }
            //  判断支付交易状态.
            try {
                if ("TRADE_SUCCESS".equals(tradeStatus)||"TRADE_FINISHED".equals(tradeStatus)){
                    //  修改交易记录状态.
                    //  修改的字段： trade_no=支付宝交易记录。payment_status = PAID callback_time callback_content
                    //  根据条件：a. outTradeNo,paymentType  b.paymentInfoQuery.getId();
//                    this.paymentService.updatePaymentStatus(outTradeNo,PaymentType.ALIPAY.name(),paramsMap);
                    this.paymentService.updatePaymentStatus(paymentInfoQuery.getId(),paramsMap);
                    //  采用异步形式发送消息给订单-通知订单修改状态--订单发送消息给库存实现减库存操作.
                    return "success";
                }
            } catch (Exception e) {
                //  当出现异常的时候删除notify_id;
                this.redisTemplate.delete(notifyId);
                e.printStackTrace();
            }
        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            return "failure";
        }
        return "failure";
    }

    //  退款接口：
    @GetMapping("refund/{orderId}")
    public Result refund(@PathVariable Long orderId){
        //  调用退款接口
        Boolean flag = this.alipayService.refund(orderId);
        if (flag){
            return Result.ok(flag);
        }else {
            return Result.fail(flag);
        }

    }

    /**
     * 关闭支付宝交易记录
     * @param orderId
     * @return
     */
    @GetMapping("closePay/{orderId}")
    public Boolean closePay(@PathVariable Long orderId){
        //  调用服务层方法
        return this.alipayService.closePay(orderId);
    }

    /**
     * 查询交易记录
     * @param orderId
     * @return
     */
    @GetMapping("checkPayment/{orderId}")
    public Boolean checkPayment(@PathVariable Long orderId){
        return this.alipayService.checkPayment(orderId);
    }

    //  查询是否有交易记录接口：
    @GetMapping("/getPaymentInfo/{outTradeNo}")
    public PaymentInfo getPaymentInfo(@PathVariable String outTradeNo){
        //  调用服务层方法。
        return this.paymentService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
    }

}
